package org.example.framework.protocol.http;


import org.apache.commons.io.IOUtils;
import org.example.framework.Invocation;
import org.example.framework.register.LocalRegister;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class HttpServerHandler {


    public void handler(HttpServletRequest req, HttpServletResponse resp){
        try {
            // 为什么获取输入流后反序列化获取对象流能被强转成这个自定义的对象
            Invocation invocation = (Invocation) new ObjectInputStream(req.getInputStream()).readObject();
            String interfaceName = invocation.getInterfaceName();
            String methodName = invocation.getMethodName();
            String version = invocation.getVersion() == null ? "" : invocation.getVersion();
            // 执行 反射
            Class<?> clazz = LocalRegister.get(interfaceName+version);
            Method method = clazz.getMethod(methodName, invocation.getParamTypes());
            String result = (String) method.invoke(clazz.newInstance(), invocation.getParams());

            IOUtils.write(result,resp.getOutputStream());

        } catch (IOException | ClassNotFoundException | NoSuchMethodException | InstantiationException |
                 IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
}
